import requests
import json
import urllib
import hashlib
import os
import random
import string
import base64

cstr = 'QWERTYUIOPASDFGHJKLZXCVBNMzyxwvutsrqponmlkjihgfedcba!@#$%^&*()'

def GetFileMd5(filename):
    if not os.path.isfile(filename):
        return
    myhash = hashlib.md5()
    f = open(filename,'rb')
    while True:
        b = f.read(8096)
        if not b :
            break
        myhash.update(b)
    f.close()
    return myhash.hexdigest()

def encryption(buffer):
    # original text
    a = str(buffer)

    # hex
    a = a.encode('hex')

    # base64
    a = (base64.encodestring(a))[0:-1]

    # confusion
    a = ''.join(random.sample(cstr, 5)) + a + ''.join(random.sample(cstr, 5))

    # base64
    a = (base64.encodestring(a))[0:-1]

    return a

def decryption(buffer):
    # de base64
    b = base64.decodestring(str(buffer))

    # de confusion
    b = b[5:]
    b = b[0:-5]

    # de base64
    b = base64.decodestring(b)

    # de hex
    b = b.decode('hex')

    return b


# # upload data
# targetFile = 'E:\\DemoData\\FDS\\data11.fds'
# md5 = GetFileMd5(targetFile)
# r = requests.get("http://172.21.212.30:8062/data?md5=" + md5)
# jsData = json.loads(r.text)
# if jsData['result'] == 'suc':
#     if(jsData['data'] <> ''):
#         pwd = jsData['data']['d_pwd']
#         pwd = decryption(decryption(pwd))
#         print('successful in finding data, ID: [' + str(jsData['data']['id'] + '] , password: [' + pwd + ']'))
#     else:
#         data = {"datatag" : "test", "pwd" : "false"}
#         files = {  
#             "datafile" : open(targetFile, "rb")  
#         }
#         r = requests.post("http://172.21.212.30:8062/data", data, files=files)
#         jsData = json.loads(r.text)
#         if jsData['result'] == 'suc':
#             pwd = jsData['data']['d_pwd']
#             pwd = decryption(decryption(pwd))
#             print('successful in uploading data, ID: [' + str(jsData['data']['id'] + '] , password: [' + pwd + ']'))

# # download data
# dataid = "5c66d623c969490810fd58ce"
# pwd = "33c70ae0-0f7a-11e9-8279-cfe390f697d3"
# pwd_c = encryption(pwd)

# print pwd_c
# filepath = "E:\\DemoData\\GeoModeling\\PyRF\\data\\5c66d623c969490810fd58ce.fds"
# urllib.urlretrieve("http://172.21.212.30:8062/data/" + dataid, filepath)